package ioDemo

import (
	"io"
	"log"
	"os"
	"path"
	"strings"
)

const (
	SOURCE = "D:\\iotest\\source"
	DESK   = "D:\\iotest\\desk"
)

func CopyToDir() {
	filePathList := GetResource(SOURCE)
	for _, filePath := range filePathList {
		_, fileName := path.Split(filePath)
		destFilePath := DESK + "/" + fileName
		CopyFunc(destFilePath, filePath)
	}
}

func GetResource(sourcePath string) []string {
	dir, err := os.ReadDir(sourcePath)
	if err != nil {
		log.Fatal(err)
	}
	list := make([]string, 0)
	for _, entry := range dir {
		if entry.IsDir() {
			continue
		}
		fullname := strings.Trim(sourcePath, "/") + "/" + entry.Name()
		list = append(list, fullname)
	}
	return list
}

func CopyFunc(destFilePath string, resourceFilePath string) (int64, error) {
	src, err := os.Open(resourceFilePath)
	if err != nil {
		log.Fatal(err)
	}
	defer src.Close()
	dst, err := os.OpenFile(destFilePath, os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatal(err)
	}
	defer dst.Close()
	return io.Copy(dst, src)
}
